'''
The MIT License (MIT)

Copyright (c) 2016 fatal_error

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

from threading import Lock
from flask import Flask, request
from random import randint
from json import dumps, loads
from time import strptime, time, localtime, mktime, sleep
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import and_
import os

databasePath = r'E:\database.db'

webApplication = Flask(__name__)
webApplication.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + databasePath
database = SQLAlchemy(webApplication)
SECURITY_CODE = 'n427yd48r2guy34s'

class Stat(database.Model):
    id = database.Column(database.Integer, primary_key=True)
    timeStamp = database.Column(database.Integer, unique=False)
    jsonstr = database.Column(database.String(512), unique=False)

    def __init__(self, timeStamp, jsonstr):
        self.timeStamp = timeStamp
        self.jsonstr = jsonstr

    def __repr__(self):
        return self.jsonstr

def timeStamp():
    return int(time.time())

def generateRandomJSONData(ts):
    a = {}
    a['sunlight'] = randint(10, 70)
    a['flame'] = randint(20, 90)
    a['temperature'] = randint(10, 95)
    a['gases'] = randint(10,95)
    a['timeStamp'] = ts
    a['human'] = randint(0,100) < 40
    return dumps(a)

def fill_data(count):
    start_timestamp = database.session.query(Stat.id).count() + 1
    while count > 0:
        temp = generateRandomJSONData(start_timestamp)
        start_timestamp = start_timestamp + 1
        count = count - 1
        database.session.add(Stat(start_timestamp-1, temp))
    database.session.commit()

def convertjson(array):
    barry = []
    for x in array:
        barry.append(loads(str(x)))
    dictionary = {}.fromkeys(barry[0].keys())
    for key in dictionary.iterkeys():
        dictionary[key] = []
    for x in barry:
        for key in dictionary.iterkeys():
            dictionary[key].append(x[key])
    return dumps(dictionary)

@webApplication.route('/data/query_<int:start>_<int:end>_<int:count>')
def data_query(start, end, count):
    arr = None
    if not count:
        if not start and end:
            arr = Stat.query.filter(Stat.timeStamp < end).all()
        elif not end and start:
            arr = Stat.query.filter(Stat.timeStamp > start).all()
        elif start and end:
            arr = Stat.query.filter(and_(Stat.timeStamp > start, Stat.timeStamp < end)).all()
    else:
        if not start and end:
            arr = Stat.query.filter(Stat.timeStamp < end).limit(count).all()
        elif not end and start:
            arr = Stat.query.filter(Stat.timeStamp > start).limit(count).all()
        elif start and end:
            arr = Stat.query.filter(and_(Stat.timeStamp > start, Stat.timeStamp < end)).limit(count).all()
        elif not start and not end:
            arr = Stat.query.limit(count).all()
    if not arr:
        return 'E'
    else:
        return convertjson(arr)

@webApplication.route('/data/iquery_<int:start>_<int:end>_<int:count>')
def data_iquery(start, end, count):
    arr = None
    if not count:
        if start and not end:
            arr = Stat.query.filter(Stat.timeStamp > start).all()
        elif not start and end:
            arr = Stat.query.filter(Stat.timeStamp < end).all()
        elif start and end:
            arr = Stat.query.filter(and_(Stat.timeStamp > start, Stat.timeStamp < end)).all()
    else:
        if not start and end:
            arr = Stat.query.order_by(Stat.timeStamp.desc()).filter(Stat.timeStamp < end).limit(count).all()
            arr.reverse()
        elif not end and start:
            arr = Stat.query.order_by(Stat.timeStamp.desc()).filter(Stat.timeStamp > start).limit(count).all()
            arr.reverse()
        elif start and end:
            arr = Stat.query.order_by(Stat.timeStamp.desc()).filter(and_(Stat.timeStamp < end, Stat.timeStamp > start)).limit(count).all()
            arr.reverse()
        elif not start and not end:
            arr = Stat.query.order_by(Stat.timeStamp.desc()).limit(count).all()
            arr.reverse()
    if not arr:
        return 'E'
    return convertjson(arr)

@webApplication.route('/data/post', methods=['POST'])
def push_data():
    if request.form['code'] == SECURITY_CODE:
    	rawjson = request.form['submition']
    	decodedjson = loads(rawjson)
    	database.session.add(Stat(decodedjson['timeStamp'], rawjson))
    	database.session.commit()
    	return 'T'
    return 'E'

@webApplication.route('/')
def get_home_page():
    return webApplication.send_static_file('homepage.html')

@webApplication.route('/favicon.ico')
def get_icon():
    return webApplication.send_static_file('favicon.ico')

@webApplication.route('/static/<staticfile>')
def get_static_file(staticfile):
    return webApplication.send_static_file(staticfile)

if __name__ == '__main__':
    webApplication.run(host='0.0.0.0', port=80)